<?php

namespace app\admin\model\order;

use app\api\model\plus\agent\Order as AgentOrderModel;
use app\api\model\settings\DicModel;
use app\api\model\user\User as UserModel;
use app\common\enum\order\OrderPayStatusEnum;
use app\common\enum\order\OrderPayTypeEnum;
use app\common\library\sms\Driver as SmsDriver;
use app\common\model\admin\User;
use app\common\model\order\Order;
use app\common\model\order\OrderTrade;
use app\common\model\order\OrderTrade as OrderTradeModel;
use app\common\model\settings\Setting as SettingModel;
use app\common\model\store\Clerk;
use app\common\service\product\factory\ProductFactory;
use app\common\model\user\BalanceLog as BalanceLogModel;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
use think\Model;


/**
 * 订单模型
 */
class OrderModel extends Order
{

    // 订单模型
    public $model;
    // 当前用户信息
    private $user;

    public function paySuccess($order_no)
    {
        $model = new static();
//        $order = $model->where(['order_no' => $order_no])->find();
//        if (empty($order)) {
//            $ot = OrderTrade::listAll(['out_trade_no' => $order_no]);
//            foreach ($ot as $item) {
//                $order = $model->where(['order_id' => $item['order_id']])->find();
//                $item->save([
//                    "pay_status"=>20
//                ]);
//                $order->save([
//                    'pay_status' => OrderPayStatusEnum::SUCCESS,
//                    'delivery_status' => 10,
//                    'order_status' => 10
//                ]);
//            }
//        } else {
//            if ($order['pay_status'] != OrderPayStatusEnum::PENDING) {
//                $order->save([
//                    'pay_status' => OrderPayStatusEnum::SUCCESS,
//                    'delivery_status' => 10,
//                    'order_status' => 10
//                ]);
//            }
//        }
        $model->transaction(function () use ($order_no) {
            $orderList = OrderTradeModel::detailWithOrder(['out_trade_no' => $order_no, 'pay_status' => 10]);
//        $orderList = OrderTradeModel::detailWithOrder(['out_trade_no' => $order_no]);
            $orderTradeInfo = OrderTradeModel::where('out_trade_no', '=', $order_no)
                ->where('pay_status', '=', 10)
                ->find();
            $totalPrice = round($orderTradeInfo['balance'] + $orderTradeInfo['online_money'], 2);
            foreach ($orderList as $order) {
                $balance = 0;
                $online_money = 0;
                if ($orderTradeInfo['balance'] > 0) {
                    $balance = round($order['pay_price'] / $totalPrice * $orderTradeInfo['balance'], 2);
                }
                if ($orderTradeInfo['online_money'] > 0) {
                    $online_money = round($order['pay_price'] / $totalPrice * $orderTradeInfo['online_money'], 2);
                }
                $payInfo['balance'] = $balance;
                $payInfo['online_money'] = $online_money;
                $this->model = $order;
                // 获取用户信息
                $this->user = UserModel::detail($this->model['user_id']);
                $payType = 'wx';
                $this->paySuccessFin($payType, [], $payInfo);
                //拼团不发短信
                if ($order['order_source'] != 30) {
                    //发送骑手短信通知
                    $clist = Clerk::where(['store_id' => $order['store_id'], 'is_send' => 1, 'is_delete' => 0])->select();
                    $time = DicModel::listAll(['type' => 'sendTime'], [], 'sort_num desc');
                    foreach ($clist as $citem) {
                        $smsConfig = SettingModel::getItem('sms', '10001');
                        $send_template = 'SMS_464455660';
                        $SmsDriver = new SmsDriver($smsConfig);
                        $mobile = $citem['mobile'];
                        $send_data = [
                            'time' => $time[0]['value']
                        ];
                        //$flag = $SmsDriver->sendSms($mobile, $send_template, $send_data);
                    }
                }
            }
            //更新trade为已支付
            (new OrderTradeModel())->where('out_trade_no', '=', $order_no)->save([
                'pay_status' => 20,
                'pay_time' => time()
            ]);
        });


    }

    public function paySuccessFin($payType, $payData = [], $payInfo = [])
    {
        // 更新付款状态
        $status = $this->updatePayStatus($payType, $payData, $payInfo);
        // 订单支付成功行为
        if ($status == true) {
            // 获取订单详情
            $detail = \app\api\model\order\Order::getUserOrderDetail($this->model['order_id'], $this->user['user_id']);
            // 记录分销商订单
            if ($detail['is_agent'] == 1) {
                AgentOrderModel::createOrder($detail);
            }
            event('PaySuccess', $detail);
        }
    }

    private function updatePayStatus($payType, $payData = [], $payInfo = [])
    {
        // 事务处理
        $this->model->transaction(function () use ($payType, $payData, $payInfo) {
            // 更新订单状态
            $this->updateOrderInfo($payType, $payData, $payInfo);
            // 累积用户总消费金额
            $this->setIncPayMoney($this->model['pay_price']);
            // 记录订单支付信息
            $this->updatePayInfo();
            //更新直播销量
//            $this->updateLiveSales();
        });
        return true;
    }

    private function updateOrderInfo($payType, $payData, $payInfo)
    {
        // 更新商品库存、销量
        ProductFactory::getFactory($this->model['order_source'])->updateStockSales($this->model['product']);
        // 整理订单信息
        $order = [
            'pay_type' => ($payType=='wx')?20:$payType,
            'pay_status' => 20,
            'pay_time' => time(),
        ];
        if ($payInfo) {
            $order['balance'] = $payInfo['balance'];
            $order['online_money'] = $payInfo['online_money'];
        }
        if ($payType != OrderPayTypeEnum::BALANCE && isset($order['online_money']) && $order['online_money'] == 0) {
            $order['pay_type'] = OrderPayTypeEnum::BALANCE;
        }
        $order['pay_source'] = 'wx';
//        if (isset($payData['attach'])) {
//            $attach = json_decode($payData['attach'], true);
//            if (isset($attach['pay_source'])) {
//                $order['pay_source'] = $attach['pay_source'];
//            }
//        }
//        if ($payType == OrderPayTypeEnum::WECHAT || $payType == OrderPayTypeEnum::ALIPAY) {
//            $order['transaction_id'] = $payData['transaction_id'];
//        }
        // 更新订单状态
        return $this->model->save($order);
    }

    public function setIncPayMoney($money)
    {
        return $this->user->where('user_id', '=', $this->user['user_id'])->inc('pay_money', $money)->update();
    }

    private function updatePayInfo()
    {
        // 余额支付
        if ($this->model['balance'] > 0) {
            // 更新用户余额
            (new UserModel())->where('user_id', '=', $this->user['user_id'])
                ->dec('balance', $this->model['balance'])
                ->update();
            BalanceLogModel::add(BalanceLogSceneEnum::CONSUME, [
                'user_id' => $this->user['user_id'],
                'money' => -$this->model['balance'],
                'app_id' => $this->model['app_id'],
            ], ['order_no' => $this->model['order_no']]);
        }
    }

}
